package org.dreamwork.jasmine2.engine;

import org.dreamwork.misc.MimeType;
import org.dreamwork.misc.MimeTypeManager;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-11-5
 * Time: 14:59:36
 */
public class DownloadManager extends HttpServlet {
    public File downloadDir;
    private File basedir;
    private static final int MAX_LENGTH = 10240;

    @Override
    public void init () throws ServletException {
        ServletContext context = getServletContext ();
        basedir = (File) context.getAttribute (JasmineEngine.J2EE_TEMP_DIR);
        downloadDir = new File (basedir, "downloads");
        if (!downloadDir.exists ()) downloadDir.mkdirs ();
    }

    @Override
    protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath ();
        String contextPath = request.getContextPath ();
        String uri = URLDecoder.decode (request.getRequestURI (), "utf-8");
        String prefix = contextPath + "/" + path;
        prefix = prefix.replace ("//", "/");

        path = uri.substring (prefix.length ());

        File file = new File (downloadDir, path);
        if (!file.exists ()) {
            response.sendError (HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        if (!file.canRead ()) {
            response.sendError (HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        String contentType = "application/octet-stream";
        int pos = path.lastIndexOf ('.');
        if (pos != -1) {
            String ext = path.substring (pos + 1);
            MimeType type = MimeTypeManager.getMimeType (ext);
            if (type != null)
                contentType = type.getName ();
        }
        response.setContentType (contentType);

        pos = path.lastIndexOf ('/');
        String fileName = path.substring (pos + 1);
        response.setHeader ("Content-Disposition", "attachment; filename=" + new String (fileName.getBytes (), "iso-8859-1"));
        response.setHeader ("Content-Length", String.valueOf (file.length ()));
        response.setHeader ("Last-Modified", new Date (file.lastModified ()).toString ());
        response.setHeader ("X-Powered-By", "Jasmine2");

        int length = Math.max (MAX_LENGTH, (int)file.length ());
        byte[] buff = new byte[length];
        FileInputStream fis = new FileInputStream (file);
        OutputStream os = response.getOutputStream ();
        try {
            while ((length = fis.read (buff)) != -1)
                os.write (buff, 0, length);
        } finally {
            fis.close ();
            os.flush ();
            response.flushBuffer ();
        }
    }
}